package com.zxw.cloud.gateway.route;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Properties;
import java.util.concurrent.Executor;

@Component
//@RefreshScope
public class DynamicRouteServiceImplByNacos  implements CommandLineRunner {

    private static Logger logger = LoggerFactory.getLogger(DynamicRouteServiceImplByNacos.class);

    @Value("${nacos.dataId}")
    private  String dataId;

    @Value("${nacos.group}")
    private  String group;

    @Value("${nacos.namespace: }")
    private  String namespace;

    @Value("${spring.cloud.nacos.config.server-addr:nacos.zcloud.com}")
    private  String serverAddr;

    @Autowired
    private DynamicRouteServiceImpl dynamicRouteService;

//    @Bean
//    public String routeServiceInit() {
//        logger.info("-------------------------------------------------------------------------------");
//        logger.info("dataId:{}",dataId);
//        logger.info("group:{}",group);
//        logger.info("serverAddr:{}",serverAddr);
//        logger.info("namespace:{}",namespace);
//        dynamicRouteByNacosListener(dataId,group,serverAddr,namespace);
//        return "success";
//    }

    /**
     * 监听Nacos Server下发的动态路由配置
     * @param dataId
     * @param group
     */
    public void dynamicRouteByNacosListener (String dataId, String group,String serverAddr,String namespace){
        try {
            if (group == null || group == ""){
                logger.info("路由group配置为null");
                return;
            }
            if (dataId == null || dataId == ""){
                logger.info("路由dataId配置为null");
                return;
            }

            ConfigService configService;
            if (StringUtils.isEmpty(namespace)){
                configService = NacosFactory.createConfigService(serverAddr);
            }else {
                Properties properties = new Properties();
                properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
                properties.put(PropertyKeyConst.NAMESPACE, namespace);
                configService = NacosFactory.createConfigService(properties);
            }

            String content = configService.getConfig(dataId, group, 5000);
            logger.info("nacos初始化监听,{}",content);
            //初始化路由
            if(StringUtils.isNotEmpty(content)){
                List<RouteDefinition> list = JSONObject.parseArray(content, RouteDefinition.class);
                list.forEach(definition->{
                    dynamicRouteService.update(definition);
                });
            }
            configService.addListener(dataId, group, new Listener()  {
                @Override
                public void receiveConfigInfo(String configInfo) {
                    try {
                        List<RouteDefinition> list = JSONObject.parseArray(configInfo, RouteDefinition.class);
                        list.forEach(definition->{
                            dynamicRouteService.update(definition);
                        });
                    }catch (Exception e){
                        logger.error("更新配置出错:",e);
                    }
                }
                @Override
                public Executor getExecutor() {
                    return null;
                }
            });
        } catch (NacosException e) {
            logger.error("初始化nacos监听出错:",e);
        }
    }

    @Override
    public void run(String... args) throws Exception {
        logger.info("-------------------------------------------------------------------------------");
        logger.info("dataId:{}",dataId);
        logger.info("group:{}",group);
        logger.info("serverAddr:{}",serverAddr);
        logger.info("namespace:{}",namespace);
        dynamicRouteByNacosListener(dataId,group,serverAddr,namespace);
    }
}
